let express = require("express");
let path = require("path");
let fs = require("fs");
const router = express.Router();
const format = require("../public/retention");
const connect = require("../config/config.js");
const log4js  = require("../config/log.js");
let logger=log4js.getLogger("info");

//角色阵容练度
router.post("/rolezr", (req, res) => {
	let uid = parseInt(req.body.uid);
	let map = new Map();
	let map1 = new Map();
	let counts = 0;let percentage_of_times = 0;let arr = [];let uid_s = '';
	let file = path.join(__dirname, '../map/role_attr.json');
	//读取json文件
	fs.readFile(file, 'utf8', function(err, data) {
		if (err) {
			res.send('文件读取失败');
		} else {
			let role_attr = JSON.parse(data);
			role_attr.forEach(item => {
				map.set(item.role_id, item.campType);
				map1.set(item.role_id, item.name);
			});
			connect(function(err, db) {
				if (err) {
					logger.info("数据库链接失败！")
				} else {
					db.collection("userinfo").aggregate([{
							$match: {
								$and: [{
									uid: uid
								}]
							}
						},
						{
							$unwind: "$role_format"
						},
						{
							$group: {
								_id: {
									uid: '$uid',
									in_crystal: '$role_format.in_crystal',
									role_id: '$role_format.role_id',
									role_level: '$role_format.role_level',
									role_power: '$role_format.role_power'
								},
								count: {
									$sum: 1
								}
							}
						}
					]).toArray(function(err, result) {
						if (err) {
							logger.info('error:' + err);
							return;
						} else {
							result.forEach((item) => {
								counts += item.count;
								uid_s = item._id.uid;
							});
							result.forEach((item) => {
								percentage_of_times = item.count / counts.toFixed(6);
								let role_id = map1.get(item._id.role_id.toString());
								let in_crystal = item._id.in_crystal.toString();
								if (in_crystal === "true") {
									in_crystal = "是";
								} else {
									in_crystal = "否";
								}
								let role_level = item._id.role_level;
								let campType = map.get(item._id.role_id.toString());
								let role_power = item._id.role_power;
								let obj = {
									uid: uid_s,
									role_id: role_id,
									in_crystal: in_crystal,
									role_level: role_level,
									campType: campType,
									role_power: role_power,
									percentage_of_times: Math.round(percentage_of_times * 10000) / (100.0).toFixed(2) + "%",
								};
								arr.push(obj);
							});
							//排序
							arr.sort((a, b) => {
								return a.role_power < b.role_power ? 1 : -1
							});
							res.json({
								code: 200,
								msg: 'success',
								result: arr
							});
						}
					})
				}
			})
		}
	});
});

//玩家充值信息
router.post("/recharge", (req, res) => {
	const uid = parseInt(req.body.uid);
	let arr = [];
	let dollarAll = 0;
	connect((err, db) => {
		if (err) {
			logger.info("数据库链接失败！")
		} else {
			db.collection("recharge").find({
				$and: [{
					uid: uid
				}]
			}).toArray(function(err, data) {
				if (err) {
					return;
				} else {
					data.forEach(item => {
						dollarAll += item.dollar;
					});
					data.forEach(item => {
						let obj = {
							server_id: item.server_id,
							uid: item.uid,
							date: item.date,
							dollar: item.dollar,
							recharge_id: item.recharge_id,
							gift_id: item.gift_id
						};
						arr.push(obj);
						arr.sort((a, b) => {
							return parseFloat(a.dollar) < parseFloat(b.dollar) ? 1 : -1;
						})
					});
					res.send({
						msg: '成功',
						code: 200,
						dollarAll: dollarAll,
						result: arr
					})
				}
			});
		}
	})
});

//挂机关卡
router.post("/hangup", (req, res) => {
	let first_time = parseInt(req.body.first_time);
	let last_time = parseInt(req.body.last_time);
	let server_id = parseInt(req.body.server_id);
	let map = new Map();
	let map1 = new Map();
	let counts = 0;
	let hangup_section = 0;
	let rankName = [];
	let file = path.join(__dirname, '../map/afkcheckpint.json');
	//读取json文件
	fs.readFile(file, 'utf8', function(err, data) {
		if (err) {
			res.send('文件读取失败');
		} else {
			let afkcheckpint = JSON.parse(data);
			afkcheckpint.forEach(item => {
				let hangup_section = item.chapter_id + '-' + item.verse_id;
				map.set(item.id, hangup_section);
				map1.set(item.old_id, hangup_section);
			});
			connect((err, db) => {
				if (err) {
					logger.info("数据库链接失败！")
				} else {
					db.collection("userinfo").aggregate([{
							$match: {
								$and: [{
										afkcheckpoint: {
											"$gt": 0
										}
									},
									{
										server_id: server_id
									},
									{
										reg_time: {
											"$gte": first_time,
											"$lte": last_time
										}
									}
								],
							}
						},
						{
							$group: {
								_id: {
									afkcheckpoint: "$afkcheckpoint",
									logout_time: "$logout_time",
									server_id: "$server_id",
									login_time: "$login_time"
								},
								count: {
									$sum: 1
								}
							}
						},
						{
							$sort: {
								_id: 1
							}
						}
					]).toArray(function(err, result) {
						if (err) {
							logger.info('error:' + err);
							return;
						} else {
							//遍历数组，取出数据
							let newArr = [];
							result.forEach(item => {
								counts += item.count;
							});
							//将相同id的数据count叠加起来
							result.forEach(item => {
								const result = newArr.findIndex(ol => {
									return item._id.afkcheckpoint === ol._id.afkcheckpoint
								});
								if (result !== -1) {
									newArr[result].count = newArr[result].count + item.count
								} else {
									newArr.push(item)
								}
							});
							newArr.forEach(item => {
								if (item._id.logout_time === 0) {
									let t = item._id.login_time - 1605196800;
									if (parseInt(t) < 0) {
										//老id
										hangup_section = map1.get(item._id.afkcheckpoint.toString());
									} else {
										//新id
										hangup_section = map.get(item._id.afkcheckpoint.toString());
									}
									if (hangup_section === undefined) {
										return;
									}
									let obj = {
										level_id: item._id.afkcheckpoint,
										hangup_section: hangup_section,
										server_id: item._id.server_id,
										hangup_count: item.count,
										hangup_proportion: Math.round((item.count) / counts * 10000) / (100.0).toFixed(2) + "%"
									};
									rankName.push(obj);
									rankName.sort((a, b) => {
										return a.hangup_count < b.hangup_count ? 1 : -1;
									})
								} else {
									let t = item._id.logout_time - 1605196800;
									if (parseInt(t) < 0) {
										//老id
										hangup_section = map1.get(item._id.afkcheckpoint.toString());
									} else {
										//新id
										hangup_section = map.get(item._id.afkcheckpoint.toString());
									}
									if (hangup_section === undefined) {
										return;
									}
									let obj = {
										level_id: item._id.afkcheckpoint,
										hangup_section: hangup_section,
										server_id: item._id.server_id,
										hangup_count: item.count,
										hangup_proportion: Math.round((item.count) / counts * 10000) / (100.0).toFixed(2) + "%"
									};
									rankName.push(obj);
									rankName.sort((a, b) => {
										return a.hangup_count < b.hangup_count ? 1 : -1;
									})
								}
							});
							res.send({
								code: 200,
								msg: "success",
								result: rankName
							});	
						}
					});
				}
			})
		}
	});
});

module.exports = router;
